package handlers

import (
	"car-master/cache"
	"car-master/models"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"strconv"
	"time"
)

func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "3"))
	offset := (page - 1) * pageSize
	/*
		SELECT
		cars_orders.cid as OrderID,
		cars.title as Title,
		cars.`name` as Name,
		cars_orders.num as Num,
		cars_orders.price as Price
		FROM
		cars
		LEFT JOIN cars_orders ON cars_orders.cid=cars.id
	*/
	var arr []models.CarList
	reds_key := "car_list" + strconv.Itoa(page)
	redsData, _ := cache.Rdb.Get(cache.Ctx, reds_key).Result()
	if redsData == "" {
		models.DB.Table("cars").Select(
			"cars_orders.cid as OrderID",
			"cars.title as Title",
			"cars.`name` as Name",
			"cars_orders.num as Num",
			"cars_orders.price as Price",
		).Joins("LEFT JOIN cars_orders ON cars_orders.cid=cars.id").
			Offset(offset).Limit(pageSize).Find(&arr)
		jsonData, _ := json.Marshal(&arr)
		cache.Rdb.Set(cache.Ctx, reds_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})

}
func CarDetail(c *gin.Context) {
	id := c.Query("id")
	var arr models.CarList
	reds_key := "car_detail" + id
	redsData, _ := cache.Rdb.Get(cache.Ctx, reds_key).Result()
	if redsData == "" {
		models.DB.Table("cars").Select(
			"cars_orders.cid as OrderID",
			"cars.title as Title",
			"cars.`name` as Name",
			"cars_orders.num as Num",
			"cars_orders.price as Price",
		).Joins("LEFT JOIN cars_orders ON cars_orders.cid=cars.id").
			Where("cars.id=?", id).Find(&arr)
		jsonData, _ := json.Marshal(&arr)
		cache.Rdb.Set(cache.Ctx, reds_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}

func del(c *gin.Context) {
	id := c.Query("id")
	var arr models.CarList
	err := models.DB.Where("id=?", id).Delete(&arr).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})

}
